package com.practice.util;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class BaseDaoUtil {
    /**
     * 获取数据库连接方法
     * @return  Connection对象
     */
    public static Connection getConnection(){
        Connection conn = null;
        //创建初使化Context对象
        try {
            Context ctxt = new InitialContext();
            DataSource ds = (DataSource)ctxt.lookup("java:comp/env/jdbc/jingsheng");
            conn = ds.getConnection();//获取到连接对象
        } catch (NamingException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;
    }


    /**
     *关闭数据库连接
     * @param rs  记录集对象
     * @param pstm  发送sql语句对象
     * @param conn  连接对象
     */
    public static void closeAll(ResultSet rs,PreparedStatement pstm,Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(pstm!=null){
            try {
                pstm.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}